/**
 * inforcreation.com co.Ltd
 * 2011-10-31
 * @author MichaelHuang
 */
package com.zchat.android.app;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;

import com.zchat.android.receivers.ApplicationBootReceiver;
import com.zchat.android.receivers.DeviceNetStatusReceiver;
import com.zchat.android.receivers.LoggedInOutBroadcastReceiver;
import com.zchat.android.receivers.ReadStatusReceiver;
import com.zchat.android.service_aidl_beans.ZChatService;
import com.zchat.api.ZChat;
import com.zchat.api.log.Logger;
import com.zchat.api.util.ZChatSetting;

/**
 * @author Oliverzhu
 * 2012/6/14
 */
public class LauncherApplication extends Application {
	private static final String TAG = "LauncherApplication";
	public static final boolean DEBUG = ZChatSetting.DEBUG;
	
	public static final String PACKAGE_NAME = "com.zchat.android";
	
	/** 当前应用程序版本 */
	private String mVersion = null;
	
	/** 当前用户登录状态 */
	private boolean login = false;
	
	private SharedPreferences mPrefs;
	
	/** 当用户登录后，启动相应的服务 */
	private TaskHandler mTaskHandler;
	 
	private HandlerThread mTaskThread;
	
	private ZChat zchat; 
    
	
	@Override
	public void onCreate() {
		super.onCreate();
		mVersion = getVersionString(this);
		 // Setup Prefs 
        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        
		new ApplicationBootReceiver().register(this);
		
		new DeviceNetStatusReceiver().register(this);
		
		new ReadStatusReceiver().register(this);
		
		new LoggedInOutBroadcastReceiver().register(this);
	
		mTaskThread = new HandlerThread(TAG + "-AsyncThread");
        mTaskThread.start();
        mTaskHandler = new TaskHandler(mTaskThread.getLooper());
		
		//send application boot broadcaster
		Intent applicationBootIntent = new Intent(ApplicationBootReceiver.APPLICATION_BOOT);
		sendBroadcast(applicationBootIntent);
		
		loadZChat();
	}
	
	
	/**
	 * 设置用户当前登录状态
	 * @param login
	 */
	public void setLogin(boolean login)
	{
		this.login = login;
	}
	
	/**
	 * 得到当前用户是否登录
	 * @return
	 */
	public boolean getLogin()
	{
		return login;
	}
	
	/**
	 * 打开连接
	 */
	private void loadZChat()
	{
//		if(ZChatSetting.TEST)
//		{
//			zchat = new ZChat(ZChat.createHttpApi("10.0.2.2:8080", mVersion, false));
//		}else
//		{
//			zchat = new ZChat(ZChat.createHttpApi(mVersion, false));
//		}
		
		zchat = 
				new ZChat(
						ZChat.creatXMPPConnection(ZChat.ZCHAT_HOST, ZChat.ZCHAT_PORT));
		zchat.openXMPPConnection();
	}
	
	public ZChat getZChat(Context context)
	{
		zchat.setContext(context);
		return zchat;
	}
	
	/**
     * Constructs the version string of the application.
     * 
     * @param context the context to use for getting package info
     * @return the versions string of the application
     */
    private static String getVersionString(Context context) {
        // Get a version string for the app.
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(PACKAGE_NAME, 0);
            return PACKAGE_NAME + ":" + String.valueOf(pi.versionCode);
        } catch (NameNotFoundException e) {
            if (DEBUG) Logger.error(TAG+"-Could not retrieve package info");
            throw new RuntimeException(e);
        }
    }
    
    /**
	 * 当用户处于登录状态的时候请求开启服务
	 */
	public void requestStartService() {
        mTaskHandler.sendMessage( //
                mTaskHandler.obtainMessage(TaskHandler.MESSAGE_START_SERVICE));
    }
	
	/** 更新用户的信息:如地理位置信息 */
	public void requestUpdateUser() {
        mTaskHandler.sendEmptyMessage(TaskHandler.MESSAGE_UPDATE_USER);
    }
    
    private class TaskHandler extends Handler {

        private static final int MESSAGE_START_SERVICE = 1;
        
        private static final int MESSAGE_UPDATE_USER = 2;

        public TaskHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (DEBUG) Logger.debug(TAG + "-handleMessage: " + msg.what);

            switch (msg.what) {

                case MESSAGE_START_SERVICE:
                	Intent service = new Intent(LauncherApplication.this, ZChatService.class);
            		startService(service);
                    break;
                case MESSAGE_UPDATE_USER:
                	break;
            }
        }
    }

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
		if(DEBUG) Logger.warn(TAG+"-Device is on low memory.");
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
	}

}
